
package com.yc.damai.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yc.damai.bean.Product;
import com.yc.damai.bean.VO;
import com.yc.damai.util.DBHelper;

public class ProductDao {

	public List<Product> queryHot() {
		String sql = "select * from product where is_hot=?"
				+ " order by pid desc limit 0,10";
		// Oracle 子查询
		return DBHelper.query(sql, Product.class, 1);
	}

	public Product queryById(String pid) {
		String sql = "select * from product where pid=?";
		// Oracle 子查询
		return DBHelper.queryById(sql, Product.class, pid);
	}

	/**
	 * 
	 * @param cid
	 * @param pageIndex  页数 从 1 开始
	 * @return
	 */
	/*public List<VO> queryByType(String cid, int pageIndex) {
		String sql = "select * from product a,categorysecond b where a.csid = b.csid and b.cid = ?";
		// limit ? (从第几行开始查询)  , ? (查询多少行  12)
		sql += " limit ? , 12";
	
		return DBHelper.query(sql, VO.class, cid, pageIndex);
	}*/
	
	public Map<String,Object> queryByType(String cid, int pageIndex) {
		String sql = "select a.* from product a,categorysecond b where a.csid = b.csid and b.cid = ?";
		// limit ? (从第几行开始查询)  , ? (查询多少行  12)
		String sql1 = sql +  " limit ? , 12";
		String sql2 = "select count(*) cnt from ("+sql+") a";

		List<VO> list = DBHelper.query(sql1, VO.class, cid, (pageIndex-1)*12);
		List<Map<String,Object>> cntlist = DBHelper.query(sql2, cid);
		Object count = cntlist.get(0).get("cnt");
		
		Map<String,Object> ret = new HashMap<String,Object>();
		ret.put("list", list);
		ret.put("rows", count);
		return ret;
	}
	
	/**
	 * 同名验证
	 * @param pname
	 * @return
	 */
	public boolean has(String pname) {
		String sql = "select count(*) cnt from product where pname=?";
		//DBHelper.queryValue(sql, resultClass, params)
		List<Map<String,Object>> list = DBHelper.query(sql, pname);
		Object cnt = list.get(0).get("cnt");
		int icnt = Integer.parseInt(""+cnt);
		return icnt > 0;
		
	}

	/**
	 * 新增
	 * @param p
	 */
	public void insert(Product p) {
		String sql = "insert into product "
				+ " (pname,market_price,shop_price,image,pdesc,is_hot,csid)"
				+ " values(?,?,?,?,?,?,?)";
		DBHelper.update(sql, 
				p.getPname(),
				p.getmarketPrice(),
				p.getshopPrice(),
				p.getImage(),
				p.getPdesc(),
				p.getisHot(),
				p.getCsid());
	}
	
	/**
	 * 修改
	 * @param p
	 */
	public void update(Product p) {
		String sql = "update product "
				+ " set pname=?,market_price=?,shop_price=?,image=?,"
				+ " pdesc=?,is_hot=?,csid=?"
				+ " where pid = ?";
		DBHelper.update(sql, 
				p.getPname(),
				p.getmarketPrice(),
				p.getshopPrice(),
				p.getImage(),
				p.getPdesc(),
				p.getisHot(),
				p.getCsid(),
				p.getPid());
	}
	
	/**
	 * 	方案一:
	 *	返回当前页数据 + 总行数  => 自定义实体类
	 *	class XXX {
	 *		private List list;
	 *		private int  allRows;
	 *	
	 *	}
	 *
	 *	方案二:
	 *	使用 Map 集合
	 *	1. Map ==> json 对象
	 *	2. 方案一
	 * 
	 * 
	 * 
	 */
	

}
